/**
 * @author dx
 * @version 1.0
 * @date 2022/3/20 21:03
 * @description:
 */
public class Dichotomy {
    public  static void main(String args[]){
        int[] nums = {1,2,4,5,6,7,23,24};
        int found = search1(nums,6);
        System.out.println(found);
    }
    //左闭右闭区间
    public static int search1(int[] nums, int target){
        int left = 0,right = nums.length-1;
        while (left <= right){
            int mid = left+((right-left)>>1);  //防止溢出
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] > target)
                right = mid -1;
            else if (nums[mid] < target)
                left = left+1;
        }
        return -1;
    }
    /*while(left<right)这里使用<，left == right在区间[left,right)是没有意义的,
     if(nums[middle]>target),right更新为middle,因为当前nums[middle]不等于target，去左区间查找，而左区间是左闭右开，所以更新right为middle
     */
    public static int search2(int[] nums,int target){
        int left = 0,right = nums.length-1;
        while(left < right){
            int mid = left + ((right-left)>>1);
            if(nums[mid] == target)
                return mid;
            else if (nums[mid] > target )
                right = mid;
            else if (nums[mid] < target )
                left = mid+1;
        }
        return -1;

    }
}
